package com.mimosa.common.message;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.mimosa.common.dao.HibernateDao;
import com.mimosa.util.config.Page;
import com.mimosa.util.constant.StringConstUtil;

@Repository
public class TMessageReceiverDao extends HibernateDao<TMessageReceiver, String> {
	/**
	 * 用于分页
	 * 
	 * @param hql
	 * @param pageSize
	 * @param pageNo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Object> page(String hql, int pageSize, int pageNo) {
		Session s = getSession();
		Query query = s.createQuery(hql);
		query.setFirstResult(pageNo);
		query.setMaxResults(pageSize);
		return query.list();
	}

	/**
	 * 根据用户ID，消息类型，以及消息标题对消息列表进行过滤
	 * 
	 * @param page
	 *            分页信息对象
	 * @param msgType
	 *            消息类型
	 * @param msgTitle
	 *            消息标题
	 * @param userId
	 *            用户主键标识
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page<TMessageReceiver> findReceiveMessage(
			Page<TMessageReceiver> page, Integer msgType, String readStatus,
			String userId, String msgTitle, String projectId) {
		Criteria criteria = this.createCriteria(Restrictions.eq(
				"receiverUserId", userId));
		criteria.createAlias("siteMessage", "siteMessage");
		if (msgType != null) {
			criteria.add(Restrictions.eq("siteMessage.messageType", msgType));
		}
		if (readStatus != null) {
			criteria.add(Restrictions.eq("readStatus", readStatus));
		}
		if (StringUtils.isNotBlank(msgTitle)) {
			criteria.add(Restrictions.like("siteMessage.title",
					StringConstUtil.PERCENTAGE + msgTitle
							+ StringConstUtil.PERCENTAGE));
		}
		if (StringUtils.isNotBlank(projectId)) {
			criteria.add(Restrictions.eq("siteMessage.projectId", projectId));
		}
		page.setTotalCount((int) this.countCriteriaResult(criteria));
		this.setPageParameterToCriteria(criteria, page);
		page.setResult((List<TMessageReceiver>) criteria.list());
		return page;
	}
}